package frame.options.virtual;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JMenuItem;

import model.components.networks.virtual.VirtualNetwork;
import frame.SimulatorFrame;
import frame.networks.tables.virtual.VirtualTable;
import frame.networks.tables.virtual.VirtualTableModel;
import frame.networks.viewers.VirtualVisualizationViewersTabbedPane;
import frame.options.virtual.create.CreateVirtualWizard;

@SuppressWarnings("serial")
public class CreateVirtualMenuItem extends JMenuItem implements ActionListener
{
	private SimulatorFrame simulatorFrame;
	public SimulatorFrame getFrame(){ return simulatorFrame; }
	public void setFrame( SimulatorFrame simulatorFrame ){ this.simulatorFrame = simulatorFrame; }

	public CreateVirtualMenuItem( SimulatorFrame simulatorFrame )
	{
		this.setFrame( simulatorFrame );
		
		this.setText( "Create" );
		this.setMnemonic( KeyEvent.VK_C );
		this.setIcon( new ImageIcon( this.getClass().getResource( "/icons/create.png" ) ) );
		this.addActionListener( this );
	}
	
	@Override
	public void actionPerformed( ActionEvent actionEvent )
	{
		this.getFrame().getNetworksPanel().getNetworksTablesTabbedPane().setSelectedIndex( 1 );
		
		CreateVirtualWizard createVirtualWizard = new CreateVirtualWizard( this.getFrame() );
		
		if( createVirtualWizard.showModalDialog() == 0 )
		{
			List< VirtualNetwork > simulatorVirtualNetworks = this.getFrame().getSimulator().getVirtualNetworks();
			VirtualVisualizationViewersTabbedPane virtualVisualizationViewersTabbedPane = this.getFrame().getNetworksPanel().getVirtualNetworksVisualizationViewersTabbedPane();
			VirtualTable virtualTable = this.getFrame().getNetworksPanel().getNetworksTablesTabbedPane().getVirtualNetworksTable();
			VirtualTableModel virtualTableModel = (VirtualTableModel) virtualTable.getModel();
			SaveVirtualMenuItem saveVirtualMenuItem = this.getFrame().getOptions().getVirtualMenu().getSaveVirtualMenuItem();
			
			simulatorVirtualNetworks.clear();
			virtualVisualizationViewersTabbedPane.removeAll();
			virtualTable.removeAll();
			
			for( VirtualNetwork virtualNetwork: createVirtualWizard.getVirtualNetworks() )
			{
				simulatorVirtualNetworks.add( virtualNetwork );
				virtualVisualizationViewersTabbedPane.addVirtualNetworkTab( virtualNetwork );
				virtualTableModel.addRow( new Object[]{ virtualNetwork.getName(), virtualNetwork.getStartingDate(), virtualNetwork.getEndingDate(), virtualNetwork.getState() } );
			}
			
			virtualTableModel.refresh();
			
			if( simulatorVirtualNetworks.size() == 0 )
				saveVirtualMenuItem.setEnabled( false );
			else
				saveVirtualMenuItem.setEnabled( true );
		}
	}
	
}
